const request = require('request')
const jwt = require('jsonwebtoken')

const { query } = require('../libs/async-db')
const { wxParams } = require('../libs/config')
const { formatData } = require('../libs/utils')

const login = {
    /**
     *  获取微信授权openid
     */
    getToken: async (code) => {
        let url = `https://api.weixin.qq.com/sns/jscode2session?
                appid=${wxParams.APPID}&
                secret=${wxParams.AppSecret}&
                js_code=${code}&
                grant_type=authorization_code`
        return new Promise((resolve, reject) => {
            request.get(url, (err, res, body) => {
                if (err) {
                    reject(err)
                } else {
                    resolve(JSON.parse(body).openid)
                }
            })
        })
    },

    /**
     * 存储用户的openid
     */
    setOpenid: async (openid) => {
        let sql = '', userData = '';
        sql = `SELECT * FROM user_openid WHERE openid='${openid}';`
        userData = formatData(await query(sql, 'nba_user')).data

        if (userData.length == 0) {
            sql = `INSERT INTO user_openid (openid,token) VALUES ('${openid}','');`
            await query(sql, 'nba_user')
        }
        let result = await _setToken(openid)
        return result;
    },
}

/**
 * 存用户的token
 */
async function _setToken(openid) {
    let sql = `SELECT id FROM user_openid WHERE openid='${openid}';`
    let userid = formatData(await query(sql, 'nba_user')).data[0].id;

    let token = jwt.sign({
        name: userid
    }, wxParams.jwtSecret, {
        expiresIn: 60*60
    })
    sql = `UPDATE user_openid SET token='${token}' WHERE id=${userid};`
    let queryData = formatData(await query(sql, 'nba_user'))
    if (queryData.code == 200) {
        return {
            code: 200,
            data: {
                userid: userid,
                openid: openid,
                token: token
            }
        }
    }
}

module.exports = login